from django.dispatch import receiver
from django.db.models.signals import post_save, post_migrate, pre_delete
from .models import UserProfile, Researcher
from audit.models import AuditManagement
from django.contrib.auth.models import Group


# set default user group
@receiver(post_save, sender=UserProfile)
def post_save_user_profile_fn(sender, instance, created, **kwargs):
    if created:
        instance.groups.add(Group.objects.get(name='external_personal'))
        AuditManagement.objects.get_or_create_for_object(instance)

@receiver(post_save, sender=UserProfile)
def create_researcher_profile(sender, instance, **kwargs):
    """Create researcher profile when is_researcher is True"""
    if instance.is_researcher and not hasattr(instance, 'researcher_profile'):
        Researcher.objects.create(user=instance)

@receiver(pre_delete, sender=Researcher)
def handle_researcher_deletion(sender, instance, **kwargs):
    """Update is_researcher flag when researcher profile is deleted"""
    if instance.user.is_researcher:
        instance.user.is_researcher = False
        instance.user.save()

